package com.qishon.pc.domain.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * Created by quangui.wu on 2017/1/17.
 */
@Slf4j
@Component
public class KillProcessUtil {

    /**
     *
     * @return
     */
    public String getProcessID(String pName){
        PrintWriter pw = null;
        InputStream ii = null;
        BufferedReader br = null;
        InputStreamReader ir = null;
        log.info("process name is "+pName);
        String pid = null;
        try{
            String path = System.getProperty("user.dir");
            final File createFileName = new File(path + "\\mytempscript.vbe");
            if(createFileName.exists()?createFileName.delete():createFileName.createNewFile()){}
            pw = new PrintWriter(new FileWriter(createFileName, true), true);
            pw.println("for each ps in getobject(\"winmgmts:\\\\.\\root\\cimv2:win32_process\").instances_");
            pw.println("wscript.echo ps.handle&vbtab&ps.name");
            pw.println("next");
            pw.close();

            ii = Runtime.getRuntime().exec("cscript " + path + "\\mytempscript.vbe").getInputStream();
            ir = new InputStreamReader(ii);
            br = new BufferedReader(ir);
            String str = null;
            String[] ss = null;
            while ((str = br.readLine()) != null) {
                if (str.indexOf(pName)>0&&str.endsWith(".exe")) {
                    ss = str.split("\\s");
                    for(int i=0;i<ss.length;i+=2){
                        pid = ss[i];
                        log.info("processName= "+ss[i+1]+"and processId= "+ss[i]);
                    }
                }
            }
            ir.close();
            ii.close();
            br.close();
            return pid;
        }catch(Exception e){
            e.printStackTrace();
        }
        return "error";
    };
    /*
     * 根据PID杀死进程
     */
    public String killProcess(String pName){
        try{
            if (!this.getProcessID(pName).equals("error")){
                int mayaProcessId = Integer.parseInt(this.getProcessID(pName));
                Runtime.getRuntime().exec("taskkill /F /PID "+mayaProcessId);
                return "success";
            }else {
                log.info("PID was not found");
                return "error";
            }
        }catch(Exception e){
            e.printStackTrace();
            log.info("Kill maya process failed");
        }
        return "error";
    }

}
